package com.cn.ycy.config;


public class RedBlackTree<T extends Comparable<T>> {

    private static final boolean RED   = true;
    private static final boolean BLACK = false;

    private class Node {
        T key;
        Node left, right;
        boolean color;

        public Node(T key, boolean color) {
            this.key = key;
            this.color = color;
        }
    }

    private Node root;

    public RedBlackTree() {
        root = null;
    }

    private boolean isRed(Node x) {
        if (x == null) return false;
        return x.color == RED;
    }

    private Node rotateLeft(Node h) {
        Node x = h.right;
        h.right = x.left;
        x.left = h;
        x.color = h.color;
        h.color = RED;
        return x;
    }

    private Node rotateRight(Node h) {
        Node x = h.left;
        h.left = x.right;
        x.right = h;
        x.color = h.color;
        h.color = RED;
        return x;
    }

    private void flipColors(Node h) {
        h.color = RED;
        h.left.color = BLACK;
        h.right.color = BLACK;
    }

    private Node put(Node h, T key) {
        if (h == null) return new Node(key, RED);

        int cmp = key.compareTo(h.key);
        if (cmp < 0) h.left  = put(h.left,  key);
        else if (cmp > 0) h.right = put(h.right, key);
        else h.key = key;

        if (isRed(h.right) && !isRed(h.left))      h = rotateLeft(h);
        if (isRed(h.left)  && isRed(h.left.left))  h = rotateRight(h);
        if (isRed(h.left)  && isRed(h.right))     flipColors(h);

        return h;
    }

    public void put(T key) {
        root = put(root, key);
        root.color = BLACK;
    }

    // You can add additional methods as needed



}
